import { ElNotification } from 'element-plus'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '代码不止，交流不停' },
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/components/login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/components/register.vue'),
    meta: { title: '注册' }
  },
  {
    redirect: '/',
    path: '/main',
    name: 'Main',
    component: () => import('@/components/main.vue'),
  },
  {
    path: '/write',
    name: 'Write',
    component: () => import('@/components/write.vue'),
  },
  {
    path: '/userInfo',
    name: 'UserInfo',
    component: () => import('@/components/userInfo.vue'),
  },
  {
    path: '/read/:name',
    name: 'Read',
    component: () => import('@/components/read.vue'),
  },
  {
    path: '/tao',
    name: 'Tao',
    component: () => import('@/Tao-UI/Tao-button.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// 路由拦截，如果 token 过期了或者 没有token, 就强制跳转登录界面
router.beforeEach((to, from, next) => {
  console.log(to);
  NProgress.start()
  if (localStorage.getItem("token") || to.name == "Login" || to.name == "Register") {
    if (to.meta.title) {
      document.title = to.meta.title as string;
    }
    next();
  } else {
    ElNotification({
      title: 'Error',
      message: 'Token已过期(或未登录), 请先登录',
      type: 'error',
      duration: 2000,
    })
    next({
      path: "/login"
    })
  }
  next();
})
router.afterEach(() => {
  NProgress.done()
});

export default router
